//
//  MYRefreshControl.swift
//  Sina
//
//  Created by 王亮龙1 on 16/5/28.
//  Copyright © 2016年 lianglong. All rights reserved.
//

import UIKit
import SnapKit

enum RefreshStatue: Int {
    case Normal
    case Pulling
    case Refreshing
}


private let refreshViewHeight: CGFloat = 60


class MYRefreshControl: UIControl {
    
    
    var statue: RefreshStatue = .Normal {
        didSet {
            
            switch statue {
            case .Normal:
                arrowicon.hidden = false
                indicatorView.stopAnimating()
                tipLabel.text = "下拉加载更多"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
                
                //悬停,只有在之前的状态为加载状态时才让他悬停
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { 
                        var inset = self.scrollView!.contentInset
                        inset.top -= refreshViewHeight
                        self.scrollView?.contentInset = inset
                    })
                }
                
                
            case .Pulling:
                tipLabel.text = "准备加载"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    })
                
                
            case .Refreshing:
                tipLabel.text = "正在加载..."
                arrowicon.hidden = true
                indicatorView.startAnimating()
                
                //请求网络数据 给观察的对象主动发送对应类型的事件
                sendActionsForControlEvents(.ValueChanged)
                
                //悬停
                UIView.animateWithDuration(0.25, animations: {
                    var inset = self.scrollView!.contentInset
                    inset.top += refreshViewHeight
                    self.scrollView?.contentInset = inset
                })
            }
            
        }
    }
    

    override init(frame: CGRect) {
        
        let rect = CGRect(x: 0, y: -refreshViewHeight, width: UIScreenWidth, height: refreshViewHeight)
        
        super.init(frame: rect)
        
        backgroundColor = UIColor.yellowColor()
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //view的生命周期方法,将要移动到父视图
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if let superview = newSuperview as? UIScrollView {
            scrollView = superview
            //KVO: 添加键值观察者
            superview.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    
    //键值观察的响应方法(必须实现)
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let offsetY = scrollView?.contentOffset.y ?? 0
        if scrollView!.dragging {
            if statue == .Pulling && offsetY > -124 {
                statue = .Normal
            } else if statue == .Normal && offsetY < -124 {
                statue = .Pulling
            }
        } else {
            if statue == .Pulling {
                statue = .Refreshing
            }
        }
    }
    
    
    //改变status状态为nomel
    func endRefresh() {
        
        //悬停延迟
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.6))
        dispatch_after(time_t, dispatch_get_main_queue()) { 
            
            self.statue = .Normal
        }
    }
    
    
    
    
    //添加子控件
    private func setupUI() {
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        
        
        //设置约束
        tipLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self.snp_center)
           // make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowicon.snp_makeConstraints { (make) in
            make.right.equalTo(tipLabel.snp_left)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        indicatorView.snp_makeConstraints { (make) in
            make.center.equalTo(arrowicon.snp_center)
        }
        
        
        
        
    }
    
    
    
    
    //懒加载子控件
    
    //全局变量,给superView赋值,然后注销键值观察者
    var scrollView: UIScrollView?
    //箭头
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //提示文字
    private lazy var tipLabel: UILabel = UILabel(title: "下拉加载更多", font: 14, textColor: UIColor.darkGrayColor(), alignment: .Center)
    //菊花
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    
    
    
    
    
    //注销(移除)键值观察者
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
